from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer
import cgi
from os import curdir
from os import sep
import string
import time

from libs import htmlparser

class MyRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
           
        
            urls = self.path[1:]
            htmlers = htmlparser.htmler(url=urls)
            
            str = htmlers.getContents().encode('gbk', 'ignore')
            
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(str)
                #f.close()
            return

           
           

        except IOError:
            self.send_error(404, 'File Not Found: %s' % self.path)

    def do_POST(self):
        global rootnode
        try:
            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) #('multipart/form-data', {'boundary': '303161840321948'})
            if ctype == 'multipart/form-data':
                query = cgi.parse_multipart(self.rfile, pdict)
            self.send_response(301)
            self.end_headers()

            upfilecontent = query.get('upfile')
            print "filecontent", upfilecontent[0]
            self.wfile.write('POST OK!')
            self.wfile.write(upfilecontent[0])

        except:
            pass

def main():
    try:
        server = HTTPServer(('', 809), MyRequestHandler)
        print 'started httpserver...'
        server.serve_forever()

    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()
